package com.atguigu.spzx.server.gateway.filter;

import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import jakarta.annotation.Resource;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class SpzxLoginGlobalFilter implements GlobalFilter {
    @Resource
    RedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、判断请求是否需要校验登录状态(/api/**/auth/**)
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        AntPathMatcher matcher = new AntPathMatcher();
        //2、无需校验直接放行
        if(!matcher.match("/api/**/auth/**" , path)){
            return chain.filter(exchange);
        }
        //3、校验登录状态
        //获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        Boolean isLogin = false;
        if(!StringUtils.isEmpty(token)){
            //redisTemplate 网关中使用的没有配置键值序列化器
            // service-user配置了，导致键和值存储/查找时 序列化的方式不同
            //user:login:
            isLogin = redisTemplate.hasKey("user:login:" + token);
        }
        //校验通过放行请求
        if(isLogin){
            return chain.filter(exchange);
        }

        //校验失败拒绝放行： 给一个200的报文，响应体Result 的code值使用需要登录的code
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        //设置响应头：设置响应体格式
        response.getHeaders().add("content-type",
                MediaType.APPLICATION_JSON_UTF8_VALUE);
        //设置响应体：
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("code" , 203);
        jsonObject.addProperty("message" , "需要登录");
        DataBuffer buffer = response.bufferFactory().wrap(jsonObject.toString().getBytes());
        return response.writeWith(Mono.just(buffer));
    }
}